package com.universest.swordholder.ui.screen

import android.app.Activity
import android.content.Context
import android.view.inputmethod.InputMethodManager
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.getSelectedText
import androidx.compose.ui.text.input.getTextBeforeSelection
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import com.github.boybeak.skbglobal.SoftKeyboardGlobal
import com.universest.swordholder.R
import com.universest.swordholder.viewmodel.passage_editor.PassageEditorViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.universest.swordholder.SwordHolderApplication
import com.universest.swordholder.data.dao.Passage
import com.universest.swordholder.data.dao.Volume
import com.universest.swordholder.tools.getItemSwapped
import com.universest.swordholder.tools.lengthWithoutSpace
import com.universest.swordholder.tools.replaceFirst
import com.universest.swordholder.ui.activity.BaseActivity
import com.universest.swordholder.ui.theme.SwordHolderTheme
import com.universest.swordholder.ui.item.ConfigItemWidget
import com.universest.swordholder.ui.widget.CardDialog
import com.universest.swordholder.ui.widget.DraggableScrollHandle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.burnoutcrew.reorderable.ReorderableItem
import org.burnoutcrew.reorderable.detectReorderAfterLongPress
import org.burnoutcrew.reorderable.rememberReorderableLazyListState
import org.burnoutcrew.reorderable.reorderable
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextDecoration
import com.universest.swordholder.model.prompt.DEFAULT_WRITING_REQUIREMENTS
import com.universest.swordholder.model.textaction.AiAction
import com.universest.swordholder.model.textaction.AiActionType
import com.universest.swordholder.model.textaction.getAiActionList
import com.universest.swordholder.ui.widget.AiAnswerDialog
import com.universest.swordholder.ui.widget.ChooseDialog
import com.universest.swordholder.ui.widget.EnsureDialog
import com.universest.swordholder.ui.widget.InputPromptDialog
import com.universest.swordholder.ui.widget.ProgressMode
import com.universest.swordholder.ui.widget.TaskProgressWidget
import com.universest.swordholder.viewmodel.passage_editor.PassageEditorViewModel.UiEvent
import org.burnoutcrew.reorderable.ItemPosition

/**
 * 章节编辑器。
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun PassageEditorScreenContent(
    modifier: Modifier = Modifier,
    viewModel: PassageEditorViewModel = viewModel()
) {
    // 获取当前上下文和协程作用域
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    // 滚动状态和焦点请求器
    val scrollState = rememberScrollState()
    val focusRequester = remember { FocusRequester() }

    // 从ViewModel获取文本值
    val textValue by viewModel.textValue.collectAsStateWithLifecycle()

    // 状态变量：键盘是否可见、键盘高度、文本布局结果、文本框高度
    var isKeyboardVisible by remember { mutableStateOf(false) }
    var keyboardHeight by remember { mutableIntStateOf(0) }
    var textLayoutResult: TextLayoutResult? by remember { mutableStateOf(null) }
    var textFieldHeight by remember { mutableIntStateOf(0) }
    val passageSwitching by viewModel.passageSwitching.collectAsStateWithLifecycle()
    val passage by viewModel.currentPassage.collectAsStateWithLifecycle()

    val passageEditable by remember(passage, passageSwitching) {
        derivedStateOf {
            passage != null && !passageSwitching
        }
    }
    // 自定义字体族 - 使用竹雀仿宋字体
    val customFontFamily = FontFamily(
        Font(R.font.zhuquefangsong, FontWeight.Normal)
    )

    val book by viewModel.book.collectAsStateWithLifecycle()

    LaunchedEffect(book) {
        if (book?.bookId == -1) {
            if (context is BaseActivity) {
                context.toast(context.getString(R.string.please_choose_a_book))
                context.finish()
            }
        }
    }
    // 副作用：监听软键盘状态
    DisposableEffect(Unit) {
        val callback = object : SoftKeyboardGlobal.SoftKeyboardCallback {
            override fun onOpen(height: Int) {
                isKeyboardVisible = true
            }

            override fun onClose() {
                isKeyboardVisible = false
            }

            override fun onHeightChanged(height: Int) {
                keyboardHeight = height
            }
        }

        /*
        添加键盘监听，此处引入skb-global库，开源库地址https://github.com/boybeak/skb-global
        MIT License
        */
        SoftKeyboardGlobal.addSoftKeyboardCallback(callback)

        // 清理时移除回调
        onDispose {
            SoftKeyboardGlobal.removeSoftKeyboardCallback(callback)
        }
    }

    // 滚动到光标位置的协程函数
    val scrollToCursor = suspend {
        if (textLayoutResult != null) {
            val cursorRect = textLayoutResult!!.getCursorRect(textValue.selection.start)
            val cursorTop = cursorRect.top.toInt()
            val cursorBottom = cursorRect.bottom.toInt()

            // 获取当前可视区域的顶部和底部
            val visibleTop = scrollState.value
            val visibleBottom = scrollState.value + textFieldHeight // 估算的可视区域高度，可根据实际调整

            // 判断光标是否在可视范围内
            val isCursorVisible = cursorTop >= visibleTop && cursorBottom <= visibleBottom

            // 如果光标不在可视范围内，则滚动到光标位置
            if (!isCursorVisible) {
                scrollState.animateScrollTo(cursorTop - textFieldHeight / 2)
            }
        }
    }

    // 副作用：键盘高度变化时自动滚动到光标位置
    LaunchedEffect(keyboardHeight) {
        //当键盘显示时，滚动到光标位置，防止键盘遮挡光标。
        if (isKeyboardVisible) {
            scrollToCursor()
        }
    }

    // 主界面布局
    Box(
        modifier = modifier
            .padding(bottom = with(LocalDensity.current) { keyboardHeight.toDp() })
    ) { // 为软键盘添加内边距

        Column {
            // 文本编辑区域
            Box(
                modifier = Modifier
                    .clickable {
                        //点击空白区域时，请求焦点并移动光标到文本末尾
                        focusRequester.requestFocus()
                        val length = textValue.text.length
                        viewModel.updateTextValue(
                            textValue.copy(
                                selection = TextRange(
                                    length,
                                    length
                                )
                            )
                        )
                        // 添加弹出软键盘的代码
                        val imm =
                            context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
                        imm?.showSoftInput(
                            (context as? Activity)?.currentFocus ?: android.view.View(context), 0
                        )
                    }
                    .onGloballyPositioned { coordinates ->
                        // 记录文本框高度用于滚动计算
                        textFieldHeight = coordinates.size.height
                    }
                    .weight(1.0f)) // 占据剩余空间
            {
                // 基础文本输入框
                BasicTextField(
                    modifier = Modifier
                        .verticalScroll(scrollState) // 垂直滚动
                        .focusRequester(focusRequester) // 焦点控制
                        .padding(top = 100.dp, start = 10.dp, end = 10.dp, bottom = 30.dp) // 内边距
                        .fillMaxSize(),
                    value = textValue,
                    onValueChange = { newValue ->
                        // 文本变化时更新ViewModel
                        viewModel.updateTextValue(newValue)
                    },
                    enabled = passageEditable,
                    onTextLayout = { layoutResult ->
                        //记录文本布局结果，用于计算光标位置
                        textLayoutResult = layoutResult
                        scope.launch {
                            scrollToCursor() // 文本布局变化时滚动到光标
                        }
                    },
                    cursorBrush = SolidColor(MaterialTheme.colorScheme.onBackground), // 光标颜色
                    textStyle = MaterialTheme.typography.bodyLarge.copy(
                        fontSize = 18.sp,
                        fontFamily = customFontFamily, // 使用自定义字体
                        lineHeight = 30.sp, // 行高
                        color = MaterialTheme.colorScheme.onBackground, // 文本颜色
                    )
                )

                // 自定义可拖拽滚动条手柄
                DraggableScrollHandle(
                    modifier =
                        Modifier
                            .padding(top = 80.dp, bottom = 30.dp)
                            .align(Alignment.BottomEnd)
                            .offset(x = 10.dp)
                            .width(42.dp)
                            .fillMaxHeight(),
                    ballRadius = 21.dp,
                    lineColor = Color.Transparent,
                    ballColor = MaterialTheme.colorScheme.primaryContainer,
                    ballTriangleColor = MaterialTheme.colorScheme.onPrimaryContainer,
                    scrollState = scrollState
                )
            }

            // 文本操作工具栏
            val textActions by viewModel.textActions.collectAsStateWithLifecycle()
            val textActionScrollState = rememberScrollState()
            val actionBarAlwaysShow by viewModel.actionBarAlwaysShow.collectAsStateWithLifecycle()
            AnimatedVisibility(
                visible = actionBarAlwaysShow || isKeyboardVisible,
                enter = fadeIn() + slideInVertically(initialOffsetY = { it }),  // 淡入动画
                exit = fadeOut() + slideOutVertically(targetOffsetY = { it }),   // 淡出动画
                modifier = Modifier
                    .wrapContentHeight()
                    .fillMaxWidth()
                    .padding(0.dp)
            ) {
                Row(
                    modifier =
                        Modifier
                            .wrapContentHeight()
                            .fillMaxWidth()
                            .padding(0.dp)
                            .horizontalScroll(textActionScrollState) // 水平滚动
                            .background(color = MaterialTheme.colorScheme.primaryContainer), // 背景色
                ) {
                    // 遍历所有文本操作按钮
                    for (textAction in textActions) {
                        val textActionIcon = textAction.icon
                        val enabled = passageEditable && textAction.enabled(textValue) // 检查操作是否可用
                        Column(modifier = Modifier.wrapContentHeight()) {
                            IconButton(
                                modifier = Modifier
                                    .height(40.dp)
                                    .width(50.dp)
                                    .padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 0.dp),
                                enabled = enabled,
                                onClick = {
                                    // 点击时应用文本操作
                                    viewModel.applyTextAction(textAction)
                                },
                                content = {
                                    Icon(
                                        textActionIcon,
                                        contentDescription = textAction.actionName, // 无障碍描述
                                        tint = if (enabled) {
                                            MaterialTheme.colorScheme.onPrimaryContainer // 可用时的颜色
                                        } else {
                                            MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.38f) // 禁用时的颜色
                                        }
                                    )
                                }
                            )
                            // 操作名称文本
                            val showActionBarText by viewModel.showActionBarText.collectAsStateWithLifecycle()
                            if (showActionBarText) {
                                Text(
                                    text = textAction.actionName,
                                    modifier = Modifier.align(Alignment.CenterHorizontally),
                                    style = MaterialTheme.typography.bodySmall,
                                    fontSize = 12.sp
                                )
                            }
                        }
                    }
                }
            }
        }

        // 字符计数显示框（右上角）
        val showCharCount by viewModel.showCharCount.collectAsStateWithLifecycle()
        if (showCharCount) {
            Box(
                modifier = Modifier
                    .height(95.dp)
                    .wrapContentWidth()
                    .padding(top = 75.dp, end = 20.dp)
                    .shadow(elevation = 4.dp, shape = RoundedCornerShape(6.dp)) // 阴影效果
                    .background(
                        color = MaterialTheme.colorScheme.secondaryContainer, // 背景色
                        shape = RoundedCornerShape(6.dp) // 圆角
                    )
                    .align(Alignment.TopEnd)
            ) {
                // 文本样式定义
                val normalStyle = MaterialTheme.typography.labelMedium.copy(
                    fontWeight = FontWeight.Bold,
                    fontSize = 10.sp
                ).toSpanStyle()
                val thinStyle = MaterialTheme.typography.labelMedium.copy(
                    fontWeight = FontWeight.Thin,
                    fontSize = 10.sp
                ).toSpanStyle()

                // 计算非空白字符总数
                val totalNonWhiteTextCount = textValue.text.lengthWithoutSpace

                Text(
                    text = buildAnnotatedString {
                        // 如果没有选中文本且光标在末尾，只显示总数
                        if (textValue.selection.length == 0 && textValue.selection.end == textValue.text.length) {
                            withStyle(thinStyle) {
                                append("$totalNonWhiteTextCount")
                            }
                            return@buildAnnotatedString
                        }

                        // 计算选中的非空白字符数
                        val selectedNonWhiteTextCount =
                            textValue.getSelectedText().lengthWithoutSpace

                        if (textValue.selection.length > 0) {
                            // 有选中文本时，突出显示选中字符数
                            withStyle(normalStyle) {
                                append("$selectedNonWhiteTextCount")
                            }
                        } else {
                            // 无选中文本时，显示光标前字符数
                            withStyle(thinStyle) {
                                append(
                                    "${
                                        textValue.getTextBeforeSelection(Int.MAX_VALUE)
                                            .lengthWithoutSpace
                                    }"
                                )
                            }
                        }
                        // 显示总数
                        withStyle(thinStyle) {
                            append("/${totalNonWhiteTextCount}")
                        }
                    },
                    modifier = Modifier
                        .padding(start = 10.dp, end = 10.dp)
                        .align(Alignment.Center),
                )
            }
        }
        // 添加顶部工具栏可见性状态
        var isToolbarVisible by remember { mutableStateOf(true) }
        var previousScrollValue by remember { mutableIntStateOf(scrollState.value) }
        val scrollThreshold = with(LocalDensity.current) { 10.dp.toPx() }
        LaunchedEffect(scrollState) {
            snapshotFlow { Pair(scrollState.value, scrollState.isScrollInProgress) }
                .collect { (currentValue, isScrolling) ->
                    when {
                        // 滚动到顶部（含超出顶部）时强制显示
                        currentValue <= 0 -> {
                            isToolbarVisible = true
                            previousScrollValue = currentValue
                        }
                        // 滚动中且差值超过阈值时更新状态
                        isScrolling -> {
                            val diff = currentValue - previousScrollValue
                            when {
                                diff > scrollThreshold -> isToolbarVisible = false
                                diff < -scrollThreshold -> isToolbarVisible = true
                            }
                            previousScrollValue = currentValue
                        }
                    }
                }
        }
        // 顶部标题栏
        AnimatedVisibility(
            visible = isToolbarVisible,
            enter = slideInVertically() + fadeIn(),
            exit = slideOutVertically() + fadeOut(),
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 20.dp, start = 10.dp, end = 10.dp)
                .height(40.dp)
                .align(Alignment.TopCenter)
        ) {
            TopTitleBar(viewModel, passage, passageEditable)
        }
    }
}

@Composable
private fun TopTitleBar(
    viewModel: PassageEditorViewModel,
    passage: Passage?,
    passageEditable: Boolean
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .shadow(
                elevation = 4.dp, // 阴影高度
                shape = RoundedCornerShape(12.dp) // 与背景形状保持一致
            )
            .background(
                color = MaterialTheme.colorScheme.primaryContainer, // 背景色
                shape = RoundedCornerShape(12.dp) // 圆角
            )
    ) {
        IconButton(
            modifier = Modifier
                .align(Alignment.CenterStart)
                .padding(start = 8.dp),
            onClick = {
                viewModel.changePassageListShown()
            }
        ) {
            Icon(
                imageVector = Icons.Default.Menu,
                contentDescription = stringResource(R.string.passage_list),
            )
        }
        var titleFocusState by remember { mutableStateOf(false) }
        Box(
            modifier = Modifier
                .align(Alignment.Center)
                .padding(start = 50.dp, end = 50.dp)
                .background(if (titleFocusState) MaterialTheme.colorScheme.background else Color.Transparent)
                .fillMaxSize()
        ) {
            val editTitle by viewModel.editPassageTitle.collectAsStateWithLifecycle()
            val book by viewModel.book.collectAsStateWithLifecycle()
            val focusRequester = remember { FocusRequester() }
            if (book != null && passage != null) {
                LaunchedEffect(Unit) {
                    viewModel.uiEvent.collect {
                        when (it) {
                            is PassageEditorViewModel.UiEvent.FocusEditTitle -> {
                                focusRequester.requestFocus()
                            }

                            else -> Unit
                        }
                    }
                }
                BasicTextField(
                    value = editTitle,
                    onValueChange = {
                        viewModel.updatePassageTitle(it)
                    },
                    enabled = passageEditable,
                    singleLine = true,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .focusRequester(focusRequester)
                        .onFocusChanged {
                            titleFocusState = it.isFocused
                        }
                        .fillMaxWidth()
                        .wrapContentHeight(),
                    textStyle = MaterialTheme.typography.bodyLarge.copy(
                        color = MaterialTheme.colorScheme.onBackground,
                        textAlign = TextAlign.Center
                    ),
                    cursorBrush = SolidColor(MaterialTheme.colorScheme.onBackground),
                )
            }
        }

        // 更多选项菜单
        var expanded by remember { mutableStateOf(false) }
        Box(modifier = Modifier.align(Alignment.CenterEnd)) {
            IconButton(
                onClick = { expanded = true },
                modifier = Modifier.padding(end = 8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.MoreVert,
                    contentDescription = stringResource(R.string.more_options) // 无障碍描述
                )
            }
            // 下拉菜单
            DropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false } // 点击外部关闭
            ) {
                DropdownMenuItem(
                    text = { Text(stringResource(R.string.copy_full_passage)) },
                    onClick = {
                        viewModel.copyPassage()
                        expanded = false
                    }
                )
                DropdownMenuItem(
                    text = { Text(stringResource(R.string.view_summarize)) },
                    onClick = {
                        viewModel.showSummarizeDialog()
                        expanded = false
                    }
                )
            }
        }
    }
}

@Composable
fun SummarizeVolumeDialog(
    volume: Volume,
    viewModel: PassageEditorViewModel,
    onDismiss: () -> Unit
) {
    val summary by viewModel.getSummarizedText(volume).collectAsStateWithLifecycle("")
    var summaryText by remember(summary) { mutableStateOf(summary) }
    var check by remember(volume.summaryUse) { mutableStateOf(volume.summaryUse) }
    CardDialog(onDismissRequest = {

    }) {
        Column(
            modifier = Modifier
                .padding(15.dp)
                .fillMaxWidth()
        ) {
            Text(
                text = stringResource(R.string.volume_summary),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            // 多行文本输入框
            BasicTextField(
                value = summaryText,
                onValueChange = { summaryText = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp)
                    .border(
                        width = 1.dp,
                        color = MaterialTheme.colorScheme.outline,
                        shape = RoundedCornerShape(4.dp)
                    )
                    .padding(8.dp),
                textStyle = MaterialTheme.typography.bodyMedium.copy(
                    color = MaterialTheme.colorScheme.onSurface
                )
            )

            Row(verticalAlignment = Alignment.CenterVertically) {
                Checkbox(checked = check, onCheckedChange = {
                    check = it
                })
                Text(text = "使用摘要", modifier = Modifier.clickable(onClick = {
                    check = !check
                }))
            }

            Text(
                text = "使用卷摘要可以缩短后续生成提示词的长度，节省tokens。但会导致AI在生成内容时知道的信息减少。",
                style = MaterialTheme.typography.bodySmall,
                modifier = Modifier
                    .alpha(0.8f)
                    .padding(bottom = 16.dp)
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                val scope = rememberCoroutineScope()
                // AI生成按钮（左下方）
                var ensureSummaryDialogOpen by remember { mutableStateOf(false) }
                var nonSummaryPassageCount by remember { mutableIntStateOf(0) }
                if (ensureSummaryDialogOpen) {
                    EnsureDialog(
                        text = "需要先为${nonSummaryPassageCount}章内容生成总结，确认吗？",
                        onEnsureOrCancel = {
                            if (it) {
                                viewModel.viewModelScope.launch {
                                    viewModel.summaryPassagesSuspend(
                                        viewModel.getNonSummaryPassagesNeed(
                                            volume
                                        )
                                    )
                                    val text = viewModel.summaryVolumeSuspend(volume)
                                    summaryText = text
                                }
                            }
                            ensureSummaryDialogOpen = false
                        })
                }
                IconButton(
                    onClick = {
                        scope.launch {
                            val list = viewModel.getNonSummaryPassagesNeed(volume)
                            if (list.isNotEmpty()) {
                                nonSummaryPassageCount = list.size
                                ensureSummaryDialogOpen = true
                                return@launch
                            }
                            val text = viewModel.summaryVolumeSuspend(volume)
                            summaryText = text
                        }
                    }
                ) {
                    Icon(
                        imageVector = Icons.Default.AutoAwesome,
                        contentDescription = stringResource(R.string.ai_generate)
                    )
                }
                Box(modifier = Modifier.weight(1f))
                // 取消按钮
                Button(
                    onClick = {
                        onDismiss()
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color.Transparent,
                        contentColor = MaterialTheme.colorScheme.onBackground
                    )
                ) {
                    Text(stringResource(R.string.cancel))
                }
                // 确定按钮（右下方）
                Button(
                    onClick = {
                        viewModel.saveSummarizedText(volume, summaryText)
                        viewModel.setVolumeUseSummary(volume, check)
                        onDismiss()
                    }
                ) {
                    Text(stringResource(R.string.sure))
                }
            }
        }
    }
}

@Composable
fun SummarizeDialog(viewModel: PassageEditorViewModel) {
    var showSummarizeDialog by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        viewModel.uiEvent.collect {
            when (it) {
                is PassageEditorViewModel.UiEvent.ShowSummarizeDialog -> {
                    showSummarizeDialog = true
                }

                else -> Unit
            }
        }
    }
    if (!showSummarizeDialog) return
    val passage by viewModel.currentPassage.collectAsStateWithLifecycle()
    val summaryPassage = passage
    if (summaryPassage == null) return
    val summary by viewModel.getSummarizedText(summaryPassage).collectAsStateWithLifecycle("")
    var summaryText by remember(summary) { mutableStateOf(summary) }
    CardDialog(onDismissRequest = {

    }) {
        Column(
            modifier = Modifier
                .padding(15.dp)
                .fillMaxWidth()
        ) {
            Text(
                text = stringResource(R.string.summarize),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            // 多行文本输入框
            BasicTextField(
                value = summaryText,
                onValueChange = { summaryText = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp)
                    .border(
                        width = 1.dp,
                        color = MaterialTheme.colorScheme.outline,
                        shape = RoundedCornerShape(4.dp)
                    )
                    .padding(8.dp),
                textStyle = MaterialTheme.typography.bodyMedium.copy(
                    color = MaterialTheme.colorScheme.onSurface
                )
            )
            Text(
                text = "章节摘要会被用于生成提示词，帮助AI进行续写。如果你要为本章自动生成摘要，需要先为前面的章节生成摘要。",
                style = MaterialTheme.typography.bodySmall,
                modifier = Modifier
                    .alpha(0.8f)
                    .padding(bottom = 16.dp, top = 7.dp)
            )
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                val scope = rememberCoroutineScope()
                // AI生成按钮（左下方）
                var ensureSummaryDialogOpen by remember { mutableStateOf(false) }
                var nonSummaryPassageCount by remember { mutableIntStateOf(0) }
                if (ensureSummaryDialogOpen) {
                    EnsureDialog(
                        text = "在该章之前尚有${nonSummaryPassageCount}章未生成总结，需要先为前面的篇章生成总结，确认吗？",
                        onEnsureOrCancel = {
                            if (it) {
                                viewModel.summaryPassages(true)
                            }
                            ensureSummaryDialogOpen = false
                        })
                }
                IconButton(
                    onClick = {
                        scope.launch {
                            val list = viewModel.getNonSummaryPassagesBefore()
                            if (list.isNotEmpty()) {
                                nonSummaryPassageCount = list.size
                                ensureSummaryDialogOpen = true
                                return@launch
                            }
                            viewModel.summaryCurrentPassage()
                        }
                    }
                ) {
                    Icon(
                        imageVector = Icons.Default.AutoAwesome,
                        contentDescription = stringResource(R.string.ai_generate)
                    )
                }
                Box(modifier = Modifier.weight(1f))
                // 取消按钮
                Button(
                    onClick = {
                        showSummarizeDialog = false
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color.Transparent,
                        contentColor = MaterialTheme.colorScheme.onBackground
                    )
                ) {
                    Text(stringResource(R.string.cancel))
                }

                // 确定按钮（右下方）
                Button(
                    onClick = {
                        viewModel.saveSummarizedText(summaryPassage, summaryText)
                        showSummarizeDialog = false
                    }
                ) {
                    Text(stringResource(R.string.sure))
                }
            }
        }
    }
}

@Composable
fun AddVolumeDialog(viewModel: PassageEditorViewModel) {
    val context = LocalContext.current
    var showAddVolumeDialog by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        viewModel.uiEvent.collect { event ->
            when (event) {
                is PassageEditorViewModel.UiEvent.ShowAddVolumeDialog -> {
                    showAddVolumeDialog = true
                }

                else -> Unit
            }
        }
    }
    if (showAddVolumeDialog) {
        CardDialog(onDismissRequest = { showAddVolumeDialog = false }) {
            Column(
                modifier = Modifier.padding(20.dp),
                horizontalAlignment = Alignment.Start
            ) {
                // 标题
                Text(
                    text = stringResource(R.string.new_volume),
                    style = MaterialTheme.typography.headlineSmall,
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 卷名输入框
                var volumeName by remember { mutableStateOf("") }
                BasicTextField(
                    value = volumeName,
                    onValueChange = { volumeName = it },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp)
                        .background(
                            MaterialTheme.colorScheme.surface,
                            RoundedCornerShape(4.dp)
                        )
                        .border(
                            width = 1.dp,
                            color = MaterialTheme.colorScheme.outline,
                            shape = RoundedCornerShape(4.dp)
                        )
                        .padding(12.dp),
                    textStyle = MaterialTheme.typography.bodyLarge.copy(
                        color = MaterialTheme.colorScheme.onSurface
                    )
                )

                // 确认按钮
                Button(
                    onClick = {
                        if (volumeName.isNotBlank()) {
                            viewModel.viewModelScope.launch {
                                viewModel.createNewVolumeSuspend(volumeName)
                            }
                            showAddVolumeDialog = false
                        }
                    },
                    enabled = volumeName.isNotBlank(),
                    modifier = Modifier.align(Alignment.End)
                ) {
                    Text(stringResource(R.string.sure))
                }
            }
        }
    }
}

@Composable
fun ModifyVolumeDialog(volume: Volume, viewModel: PassageEditorViewModel, onDismiss: () -> Unit) {
    val context = LocalContext.current
    CardDialog(onDismissRequest = onDismiss) {
        Column(
            modifier = Modifier.padding(20.dp),
            horizontalAlignment = Alignment.Start
        ) {
            // 标题
            Text(
                text = "修改卷名",
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            // 卷名输入框
            var volumeName by remember(volume.name) { mutableStateOf(volume.name) }
            BasicTextField(
                value = volumeName,
                onValueChange = { volumeName = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp)
                    .background(
                        MaterialTheme.colorScheme.surface,
                        RoundedCornerShape(4.dp)
                    )
                    .border(
                        width = 1.dp,
                        color = MaterialTheme.colorScheme.outline,
                        shape = RoundedCornerShape(4.dp)
                    )
                    .padding(12.dp),
                textStyle = MaterialTheme.typography.bodyLarge.copy(
                    color = MaterialTheme.colorScheme.onSurface
                )
            )

            // 确认按钮
            Button(
                onClick = {
                    if (volumeName.isNotBlank()) {
                        viewModel.viewModelScope.launch {
                            viewModel.updateVolumeNameSuspend(volume.volumeId, volumeName)
                        }
                        onDismiss()
                    }
                },
                enabled = volumeName.isNotBlank(),
                modifier = Modifier.align(Alignment.End)
            ) {
                Text(stringResource(R.string.sure))
            }
        }
    }
}

@Composable
private fun ActionBarDialog(
    viewModel: PassageEditorViewModel,
    context: Context
) {
    var showActionBarDialog by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        viewModel.uiEvent.collect { event ->
            when (event) {
                is PassageEditorViewModel.UiEvent.ShowActionBarDialog -> {
                    showActionBarDialog = true
                }

                PassageEditorViewModel.UiEvent.Exit -> {
                    val activity = context as? Activity
                    activity?.finish()
                }

                else -> Unit
            }
        }
    }
    if (showActionBarDialog) {
        CardDialog(onDismissRequest = { showActionBarDialog = false }) {
            Column(
                modifier = Modifier.padding(20.dp),
                horizontalAlignment = Alignment.Start
            ) {
                val configItems by viewModel.configItems.collectAsStateWithLifecycle()
                for (item in configItems) {
                    val config by viewModel.getUserConfig(item).collectAsStateWithLifecycle()
                    ConfigItemWidget(
                        configItem = item,
                        onValueChange = { config, value ->
                            viewModel.setUserConfig(
                                config,
                                value
                            )
                        },
                        value = config
                    )
                }
            }
        }
    }
}

@Composable
fun PassageEditorScreen(
    modifier: Modifier = Modifier,
    viewModel: PassageEditorViewModel = viewModel()
) {
    ToastEventHandle(viewModel)
    // 控制抽屉状态
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    // 创建协程作用域用于打开/关闭抽屉（这些是挂起函数）
    val scope = rememberCoroutineScope()
    val passages by viewModel.passages.collectAsStateWithLifecycle(emptyList())
    val volumes by viewModel.volumes.collectAsStateWithLifecycle(emptyList())
    val book by viewModel.book.collectAsStateWithLifecycle()
    val context = LocalContext.current
    val passageSwitching by viewModel.passageSwitching.collectAsStateWithLifecycle()
    val editorVisible by remember {
        derivedStateOf { !passageSwitching && (book?.bookId ?: -1) != -1 }
    }
    LaunchedEffect(Unit) {
        viewModel.uiEvent.collect { event ->
            when (event) {
                is PassageEditorViewModel.UiEvent.ShowPassageListDialog -> {
                    scope.launch {
                        drawerState.open()
                    }
                }

                is PassageEditorViewModel.UiEvent.ClosePassageListDialog -> {
                    scope.launch {
                        drawerState.close()
                    }
                }

                else -> Unit
            }
        }
    }
    ModalNavigationDrawer(
        modifier = modifier,
        drawerState = drawerState,
        drawerContent = {
            ModalDrawerSheet(
                modifier = Modifier
                    .width(300.dp)
                    .fillMaxHeight()
                    .padding(0.dp),
                windowInsets = WindowInsets(0),
            ) {
                var dragReorder by remember {
                    mutableStateOf(false)
                }
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                ) {
                    // 顶部工具栏行
                    Row(
                        modifier = Modifier
                            .fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 显示书名
                        Text(
                            text = stringResource(
                                R.string.book_marks,
                                book?.bookName ?: stringResource(R.string.unknown_book)
                            ),
                            modifier = Modifier
                                .weight(1f)
                                .padding(start = 10.dp),
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.onSurface
                        )

                        // 搜索按钮
                        IconButton(onClick = {
                            // TODO: 实现搜索功能
                        }) {
                            Icon(
                                tint = MaterialTheme.colorScheme.onBackground,
                                imageVector = Icons.Default.Search,
                                contentDescription = stringResource(R.string.search)
                            )
                        }

                        // 更多选项按钮
                        var moreMenuExpanded by remember { mutableStateOf(false) }
                        IconButton(onClick = {
                            moreMenuExpanded = true
                        }) {
                            Icon(
                                tint = MaterialTheme.colorScheme.onBackground,
                                imageVector = Icons.Default.MoreVert,
                                contentDescription = stringResource(R.string.more)
                            )

                            DropdownMenu(
                                expanded = moreMenuExpanded,
                                onDismissRequest = { moreMenuExpanded = false }
                            ) {
                                if (book?.singlePassage != true) {
                                    DropdownMenuItem(
                                        text = { Text(stringResource(R.string.create_new_passage)) },
                                        onClick = {
                                            scope.launch {
                                                viewModel.createNewPassage(context.getString(R.string.default_passage_title))
                                            }
                                            moreMenuExpanded = false
                                        }
                                    )
                                    DropdownMenuItem(
                                        text = { Text(stringResource(R.string.create_new_volume)) },
                                        onClick = {
                                            viewModel.openNewVolumeDialog()
                                            moreMenuExpanded = false
                                        }
                                    )
                                    DropdownMenuItem(
                                        text = {
                                            val text = stringResource(R.string.drag_sort)
                                            Text(
                                                text = "$text${if (dragReorder) " ${stringResource(R.string.tick)}" else ""}",
                                                style = MaterialTheme.typography.bodyMedium.copy(
                                                    fontWeight = FontWeight.Bold,
                                                    textDecoration = if (dragReorder) {
                                                        TextDecoration.Underline
                                                    } else {
                                                        null
                                                    }
                                                )
                                            )
                                        },
                                        onClick = {
                                            dragReorder = !dragReorder
                                            moreMenuExpanded = false
                                        }
                                    )
                                    DropdownMenuItem(
                                        text = { Text(stringResource(R.string.volume_passage_auto_change_name)) },
                                        onClick = {
                                            viewModel.autoChangeVolumePassageName()
                                            moreMenuExpanded = false
                                        }
                                    )
                                }
                                DropdownMenuItem(
                                    text = { Text(stringResource(R.string.export_txt)) },
                                    onClick = {
                                        viewModel.exportNovel()
                                        moreMenuExpanded = false
                                    }
                                )
                            }
                        }
                    }
                    PassageTitleList(passages, scope, viewModel, volumes, dragReorder, drawerState)
                }
            }
        },
        content = {
            if (!editorVisible) {
                // 添加居中的 Loading 动画
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .wrapContentSize(Alignment.Center)
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(48.dp),
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }
            AnimatedVisibility(
                visible = editorVisible,
                modifier = Modifier
                    .fillMaxSize(),
                enter = fadeIn(),
                exit = fadeOut()
            ) {
                PassageEditorScreenContent(
                    viewModel = viewModel,
                    modifier = Modifier.fillMaxSize()
                )
            }
        },
    )
    Dialogs(viewModel, context)
}

@Composable
private fun ToastEventHandle(viewModel: PassageEditorViewModel) {
    val localContext = LocalContext.current
    LaunchedEffect(Unit) {
        viewModel.toasts.collect {
            (localContext as? BaseActivity)?.toast(it)
        }
    }
}

@Composable
private fun Dialogs(
    viewModel: PassageEditorViewModel,
    context: Context
) {
    ActionBarDialog(viewModel, context)
    AddVolumeDialog(viewModel)
    SummarizeDialog(viewModel)
    AiDialog(viewModel)
    TaskDialog(viewModel)
}

val Passage.catalogId: String
    get() = "p_${this.passageId}"

val Volume.catalogId: String
    get() = "v_${this.volumeId}"

/**
 * 显示章节标题列表的可组合函数
 *
 * @param passages 章节列表
 * @param scope 协程作用域，用于执行异步操作
 * @param viewModel 视图模型，用于处理业务逻辑
 * @param volumes 卷列表，用于组织章节结构
 */
@Composable
private fun ColumnScope.PassageTitleList(
    passages: List<Passage>,
    scope: CoroutineScope,
    viewModel: PassageEditorViewModel,
    volumes: List<Volume>,
    dragReorder: Boolean,
    drawerState: DrawerState
) {
    //这么做是为了维持一个本地的可以及时更新的状态，修改数据库再加载会造成卡顿。
    val expandStates = remember(volumes) { mutableStateMapOf<Int, Boolean>() }
    val statePassages = remember { mutableStateOf<List<Passage>>(passages) }
    //仅在passages（来自数据库的更新）发生变化时调用。这里不能直接赋值statePassages.value = passages，否则会导致抖动。
    LaunchedEffect(passages) {
        statePassages.value = passages
    }
    val stateVolumes = remember { mutableStateOf<List<Volume>>(volumes) }
    //同理。
    LaunchedEffect(volumes) {
        stateVolumes.value = volumes
    }
    // 缓存过滤后的未分卷章节
    val unassignedPassages = remember(statePassages.value) {
        statePassages.value.filter { it.volumeId == -1 }
    }

    // 缓存按 volumeId 分组的章节
    val passagesByVolume = remember(statePassages.value) {
        statePassages.value.groupBy { it.volumeId }
    }

    val reorderableState = rememberReorderableLazyListState(
        onMove = { from, to -> handleMove(from, to, statePassages, stateVolumes, viewModel) }
    )
    val state = if (dragReorder) reorderableState.listState else rememberLazyListState()
    LaunchedEffect(drawerState.isClosed) {
        if (!drawerState.isClosed) {
            val index = viewModel.computeCurrentPassageIndexInList()
            if (index >= 0) {
                state.animateScrollToItem(index)
            }
        }
    }
    LazyColumn(
        state = state,
        modifier = Modifier
            .fillMaxWidth()
            .weight(1f)
            .padding(10.dp)
            .then(
                if (dragReorder) {
                    Modifier
                        .reorderable(reorderableState)
                        .detectReorderAfterLongPress(reorderableState)
                } else {
                    Modifier
                }
            )
    ) {
        // 显示未分卷章节
        items(unassignedPassages, key = { "p_${it.passageId}" }) { passage ->
            ReorderableItem(reorderableState, key = "p_${passage.passageId}") { isDragging ->
                PassageListItemWidget(scope, viewModel, passage, dragReorder)
                HorizontalDivider(color = MaterialTheme.colorScheme.onSurfaceVariant)
            }
        }

        // 按卷组织显示章节
        for (volume in volumes) {
            val volumeId = volume.volumeId
            val expand = expandStates.getOrPut(volumeId) { true }

            item(volume.catalogId) {
                ReorderableItem(reorderableState, key = "v_${volume.volumeId}") { isDragging ->
                    VolumeListItemWidget(
                        volume = volume,
                        expand = expand,
                        onExpandChange = { expandStates[volumeId] = it },
                        dragReorder = dragReorder,
                        viewModel = viewModel
                    )
                    HorizontalDivider(color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }

            // 显示属于当前卷的所有章节
            if (expand) {
                val volumePassages = passagesByVolume[volumeId].orEmpty()
                items(volumePassages, key = { it.catalogId }) { passage ->
                    ReorderableItem(
                        reorderableState,
                        key = "p_${passage.passageId}"
                    ) { isDragging ->
                        PassageListItemWidget(scope, viewModel, passage, dragReorder)
                        HorizontalDivider(
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f)
                        )
                    }
                }
            }
        }
    }
}

/**
 * 处理拖拽移动事件的逻辑
 */
private fun handleMove(
    from: ItemPosition,
    to: ItemPosition,
    statePassages: MutableState<List<Passage>>,
    stateVolumes: MutableState<List<Volume>>,
    viewModel: PassageEditorViewModel
) {
    val fromKey = from.key as String
    val toKey = to.key as String

    when {
        fromKey.startsWith("p_") && toKey.startsWith("p_") -> handlePassageToPassageMove(
            fromKey,
            toKey,
            statePassages,
            viewModel
        )

        fromKey.startsWith("p_") && toKey.startsWith("v_") -> handlePassageToVolumeMove(
            fromKey,
            toKey,
            statePassages,
            stateVolumes,
            viewModel
        )

        fromKey.startsWith("v_") && toKey.startsWith("p_") -> handlePassageToVolumeMove(
            toKey,
            fromKey,
            statePassages,
            stateVolumes,
            viewModel
        )

        fromKey.startsWith("v_") && toKey.startsWith("v_") -> handleVolumeToVolumeMove(
            fromKey,
            toKey,
            viewModel
        )
    }
}

/**
 * 处理章节到章节的移动
 */
private fun handlePassageToPassageMove(
    fromKey: String,
    toKey: String,
    statePassages: MutableState<List<Passage>>,
    viewModel: PassageEditorViewModel
) {
    val fromId = fromKey.substring(2).toInt()
    val toId = toKey.substring(2).toInt()

    val newList = statePassages.value.getItemSwapped(
        statePassages.value.indexOfFirst { it.passageId == fromId },
        statePassages.value.indexOfFirst { it.passageId == toId }
    )
    statePassages.value = newList
    viewModel.passageListItemSwap(fromId, toId)
}

/**
 * 处理章节到卷的移动
 */
private fun handlePassageToVolumeMove(
    passageKey: String,
    volumeKey: String,
    statePassages: MutableState<List<Passage>>,
    stateVolumes: MutableState<List<Volume>>,
    viewModel: PassageEditorViewModel
) {
    val passageId = passageKey.substring(2).toInt()
    val volumeId = volumeKey.substring(2).toInt()

    val passage = statePassages.value.firstOrNull { it.passageId == passageId } ?: return

    if (passage.volumeId == volumeId) {
        handleMoveToAdjacentVolume(
            passageId,
            passage,
            volumeId,
            statePassages,
            stateVolumes,
            viewModel
        )
    } else {
        handleMoveToDifferentVolume(
            passageId,
            passage,
            volumeId,
            statePassages,
            stateVolumes,
            viewModel
        )
    }
}

/**
 * 处理移动到相邻卷的逻辑
 */
private fun handleMoveToAdjacentVolume(
    passageId: Int,
    passage: Passage,
    volumeId: Int,
    statePassages: MutableState<List<Passage>>,
    stateVolumes: MutableState<List<Volume>>,
    viewModel: PassageEditorViewModel
) {
    val volumes = stateVolumes.value
    val volumeIndex = volumes.indexOfFirst { it.volumeId == volumeId }

    if (volumeIndex <= 0) {
        movePassageToUnassigned(passageId, passage, statePassages, viewModel)
    } else {
        val adjacentVolumeId = volumes[volumeIndex - 1].volumeId
        movePassageToVolume(passageId, passage, adjacentVolumeId, statePassages, viewModel)
    }
}

/**
 * 处理移动到不同卷的逻辑
 */
private fun handleMoveToDifferentVolume(
    passageId: Int,
    passage: Passage,
    targetVolumeId: Int,
    statePassages: MutableState<List<Passage>>,
    stateVolumes: MutableState<List<Volume>>,
    viewModel: PassageEditorViewModel
) {
    val isTopMove = stateVolumes.value.indexOfFirst { it.volumeId == passage.volumeId } <
            stateVolumes.value.indexOfFirst { it.volumeId == targetVolumeId }

    movePassageToVolume(passageId, passage, targetVolumeId, statePassages, viewModel, isTopMove)
}

/**
 * 将章节移动到未分卷区域
 */
private fun movePassageToUnassigned(
    passageId: Int,
    passage: Passage,
    statePassages: MutableState<List<Passage>>,
    viewModel: PassageEditorViewModel
) {
    val newList = statePassages.value.toMutableList()
    val lastUnassignedOrder = newList.lastOrNull { it.volumeId == -1 }?.order?.let { it + 1 } ?: 0

    newList.replaceFirst(
        predicate = { it.passageId == passageId },
        newItem = passage.copy(volumeId = -1, order = lastUnassignedOrder)
    )
    newList.sortBy { it.order }

    statePassages.value = newList
    viewModel.movePassageToAnotherVolume(passageId, -1, false)
}

/**
 * 将章节移动到指定卷
 */
private fun movePassageToVolume(
    passageId: Int,
    passage: Passage,
    targetVolumeId: Int,
    statePassages: MutableState<List<Passage>>,
    viewModel: PassageEditorViewModel,
    isTopMove: Boolean = false
) {
    val newList = statePassages.value.toMutableList()
    val targetPassages = newList.filter { it.volumeId == targetVolumeId }

    val newOrder = if (isTopMove) {
        targetPassages.firstOrNull()?.order?.let { it - 1 } ?: 0
    } else {
        targetPassages.lastOrNull()?.order?.let { it + 1 } ?: 0
    }

    newList.replaceFirst(
        predicate = { it.passageId == passageId },
        newItem = passage.copy(volumeId = targetVolumeId, order = newOrder)
    )
    newList.sortBy { it.order }
    statePassages.value = newList
    viewModel.movePassageToAnotherVolume(passageId, targetVolumeId, isTopMove)
}

/**
 * 处理卷到卷的移动
 */
private fun handleVolumeToVolumeMove(
    fromKey: String,
    toKey: String,
    viewModel: PassageEditorViewModel
) {
    val fromId = fromKey.substring(2).toInt()
    val toId = toKey.substring(2).toInt()
    viewModel.swapVolumeOrder(fromId, toId)
}

/**
 * 卷标题项的可组合函数
 *
 * @param volume 卷对象，包含卷的信息
 */
@Composable
private fun VolumeListItemWidget(
    volume: Volume,
    expand: Boolean = true,
    onExpandChange: (Boolean) -> Unit = {},
    dragReorder: Boolean,
    viewModel: PassageEditorViewModel
) {
    var dropMenuExpand by remember { mutableStateOf(false) }
    Row(
        modifier = Modifier
            .height(40.dp)
            .then(
                if (dragReorder) {
                    Modifier
                } else {
                    Modifier.combinedClickable(onClick = {
                        onExpandChange(!expand)
                    }, onLongClick = {
                        dropMenuExpand = true
                    })
                }
            )
            .background(if (dragReorder) MaterialTheme.colorScheme.primaryContainer else Color.Transparent)
            .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        IconButton(onClick = { onExpandChange(!expand) }, modifier = Modifier.size(40.dp)) {
            Icon(
                tint = MaterialTheme.colorScheme.onBackground,
                imageVector = if (expand) Icons.Default.KeyboardArrowDown else Icons.AutoMirrored.Filled.KeyboardArrowRight,
                contentDescription = "展开"
            )
        }
        Text(
            text = volume.name,
            modifier = Modifier
                .weight(1f)
                .padding(start = 10.dp),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurface
        )
        var ensureRemoveDialogShow by remember { mutableStateOf(false) }
        if (ensureRemoveDialogShow) {
            EnsureDialog(
                text = stringResource(R.string.ensure_to_remove_volume),
                onEnsureOrCancel = { it ->
                    if (it) {
                        viewModel.removeVolume(volume.volumeId)
                    }
                    ensureRemoveDialogShow = false
                })
        }
        var volumeSummaryDialogShow by remember { mutableStateOf(false) }
        if (volumeSummaryDialogShow) {
            SummarizeVolumeDialog(
                volume,
                viewModel,
                onDismiss = { volumeSummaryDialogShow = false })
        }
        var showModifyVolumeNameDialog by remember { mutableStateOf(false) }
        if (showModifyVolumeNameDialog) {
            ModifyVolumeDialog(volume, viewModel) {
                showModifyVolumeNameDialog = false
            }
        }
        DropdownMenu(expanded = dropMenuExpand, onDismissRequest = { dropMenuExpand = false }) {
            DropdownMenuItem(
                text = { Text(stringResource(R.string.delete_volume)) }, onClick = {
                    ensureRemoveDialogShow = true
                    dropMenuExpand = false
                }
            )
            DropdownMenuItem(
                text = { Text("修改卷名称") }, onClick = {
                    showModifyVolumeNameDialog = true
                    dropMenuExpand = false
                }
            )
            DropdownMenuItem(
                text = { Text("卷摘要") }, onClick = {
                    volumeSummaryDialogShow = true
                    dropMenuExpand = false
                }
            )
        }
    }
}

/**
 * 章节列表项的可组合函数
 *
 * @param scope 协程作用域，用于执行异步操作
 * @param viewModel 视图模型，用于处理业务逻辑
 * @param passage 章节对象，包含章节信息
 */
@Composable
private fun PassageListItemWidget(
    scope: CoroutineScope,
    viewModel: PassageEditorViewModel,
    passage: Passage,
    dragReorder: Boolean
) {
    var dropMenuExpand by remember { mutableStateOf(false) }
    Row(
        modifier = Modifier
            .height(40.dp)
            .background(if (dragReorder) MaterialTheme.colorScheme.surfaceContainer else Color.Transparent)
            .then(
                if (dragReorder) {
                    Modifier
                } else {
                    Modifier.combinedClickable(
                        onLongClick = {
                            dropMenuExpand = true
                        },
                        onClick = {
                            // 点击章节项时，通过协程切换到指定章节
                            scope.launch {
                                viewModel.changePassage(passage.passageId)
                                viewModel.changePassageListShown(false)
                            }
                        }
                    )
                }
            )
            .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        val currentPassage by viewModel.currentPassage.collectAsStateWithLifecycle()
        val isCurrentPassage = currentPassage?.passageId == passage.passageId
        val paddingStart = if (passage.volumeId == -1) 10.dp else 40.dp
        Row(
            modifier = Modifier
                .weight(1f)
                .padding(start = paddingStart), verticalAlignment = Alignment.CenterVertically
        ) {
            if (isCurrentPassage) {
                Box(
                    modifier = Modifier
                        .padding(top = 5.dp, bottom = 5.dp, end = 5.dp)
                        .width(5.dp)
                        .fillMaxHeight()
                        .background(MaterialTheme.colorScheme.onSurface)
                )
            }
            Text(
                text = passage.title,
                modifier = Modifier
                    .wrapContentWidth(),
                style = if (isCurrentPassage)
                    MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold) else MaterialTheme.typography.bodyMedium,
            )
            var ensureRemoveDialogShow by remember { mutableStateOf(false) }
            if (ensureRemoveDialogShow) {
                EnsureDialog(
                    text = stringResource(R.string.ensure_to_remove_passage),
                    onEnsureOrCancel = { it ->
                        if (it) {
                            viewModel.removePassage(passage.passageId)
                        }
                        ensureRemoveDialogShow = false
                    })
            }
            DropdownMenu(expanded = dropMenuExpand, onDismissRequest = { dropMenuExpand = false }) {
                DropdownMenuItem(
                    text = { Text(stringResource(R.string.remove_passage)) }, onClick = {
                        ensureRemoveDialogShow = true
                        dropMenuExpand = false
                    }
                )
            }
        }
    }
}

@Composable
private fun AiDialog(viewModel: PassageEditorViewModel) {
    val scope = rememberCoroutineScope()
    var aiAction: AiAction? by remember { mutableStateOf(null) }
    var openAiDialog by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        viewModel.uiEvent.collect {
            when (it) {
                is UiEvent.OpenAiDialog -> {
                    openAiDialog = true
                }

                else -> Unit
            }
        }
    }

    var ensureDialogOpen by remember { mutableStateOf(false) }

    var ensureTitle by remember { mutableStateOf("") }

    var ensureText by remember { mutableStateOf("") }

    if (ensureDialogOpen) {
        InputPromptDialog(
            title = ensureTitle, content = ensureText,
            onDismissRequest = {
                ensureDialogOpen = false
                aiAction = null
            },
            onConfirm = { text ->
                viewModel.aiActionResultHandle(text)
                ensureDialogOpen = false
                aiAction = null
            })
    }

    var markDownDialogOpen by remember { mutableStateOf(false) }

    var markdownContent by remember { mutableStateOf("") }

    if(markDownDialogOpen){
        AiAnswerDialog(onDismiss = {
            markDownDialogOpen = false
            markdownContent = ""
            aiAction = null
        }, markdownContent)
    }

    aiAction?.let { action ->
        when (action.type) {
            AiActionType.GENERATE_TEXT -> {
                InputPromptDialog(
                    title = "请输入要续写内容的概要",
                    onDismissRequest = {
                        aiAction = null
                        openAiDialog = false
                    },
                    onConfirm = { prompt ->
                        scope.launch {
                            val str = viewModel.runAiActionSuspend(action, prompt)
                            if (!str.isBlank()) {
                                ensureTitle = "请确认续写的内容"
                                ensureText = str
                                ensureDialogOpen = true
                            }
                        }
                    })
            }

            AiActionType.REWRITE_TEXT -> {
                InputPromptDialog(
                    title = "请输入你对润色段落的文笔要求",
                    onDismissRequest = {
                        aiAction = null
                        openAiDialog = false
                    },
                    content = DEFAULT_WRITING_REQUIREMENTS,
                    onConfirm = { prompt ->
                        scope.launch {
                            val str = viewModel.runAiActionSuspend(action, prompt)
                            if (!str.isBlank()) {
                                ensureTitle = "请确认润色的内容"
                                ensureText = str
                                ensureDialogOpen = true
                            }
                        }
                    })
            }

            AiActionType.COMMENT -> {
                InputPromptDialog(
                    title = "请输入你的问题",
                    onDismissRequest = {
                        aiAction = null
                        openAiDialog = false
                    },
                    content = "请鉴赏当前章节的内容，并给出你的建议。",
                    onConfirm = { prompt ->
                        scope.launch {
                            val str = viewModel.runAiActionSuspend(action, prompt)
                            if (!str.isBlank()) {
                                markdownContent = str
                                markDownDialogOpen = true
                            }
                        }
                    })
            }

            else -> Unit
        }
    }


    if (openAiDialog) {
        val textValue by viewModel.textValue.collectAsStateWithLifecycle()
        val choices = getAiActionList().filter {
            when (it.type) {
                AiActionType.GENERATE_TEXT -> textValue.selection.start == textValue.selection.end
                AiActionType.REWRITE_TEXT -> textValue.selection.length > 0
                else -> true
            }
        }
        ChooseDialog(
            title = "请选择要使用的AI工具",
            choices = choices,
            onChoice = { index, choice ->
                aiAction = choice
                openAiDialog = false
            },
            onDismiss = { openAiDialog = false }
        )
    }
}

@Composable
fun TaskDialog(viewModel: PassageEditorViewModel) {
    val tasks = viewModel.tasks
    if (!tasks.isEmpty()) {
        CardDialog(onDismissRequest = {}) {
            Column {
                tasks.forEach { task ->
                    TaskProgressWidget(task = task, progressMode = ProgressMode.Percentage)
                }
            }
        }
    }
}

// 预览函数
@Preview
@Composable
fun PassageEditorScreenPreview() {
    SwordHolderApplication.previewContext = LocalContext.current
    SwordHolderTheme {
        PassageEditorScreen()
    }
}